﻿'use strict';

angular.module('ishaCrmApp')

    .controller('headerCtrl', ['$scope', '$location', 'stateSvc', 'googleAuthSvc', function ($scope, $location, stateSvc, googleAuthSvc) {

        $scope.header = {};

        $scope.header.menuItems = [
            { title: 'Home', link: '/', active: true },
            { title: 'Search', link: '/search', active: false }
        ];

        $scope.header.full_name = stateSvc.loginUserFullname();
        $scope.header.loggedIn = stateSvc.isAuthenticated();
        $scope.header.errorMsg = $.trim(stateSvc.lastError);

        $scope.header.login = function () {
            stateSvc.login();
            if (stateSvc.isAuthenticated()) {
                $location.path('/#/search').replace();
            }
        };

        $scope.header.logout = function () {
            stateSvc.signOut();
        }

        $scope.changeMenu = function (menuItem) {
            stateSvc.activeMenu = menuItem.title;
            $scope.updateMenu(null, menuItem.title);
            $location.path(menuItem.link);
        }

        $scope.updateMenu = function(event, menuTitle) {
            var activeMenu = menuTitle.toLowerCase();
            angular.forEach($scope.header.menuItems, function (value, key) {
                value.active = (value.title.toLowerCase() == activeMenu);
            });
        }

        $scope.initDataFromStateSvc = function() {
            $scope.header.full_name = stateSvc.loginUserFullname();
            $scope.header.loggedIn = stateSvc.isAuthenticated();
            $scope.header.errorMsg = $.trim(stateSvc.lastError);

        }
        // Event listeners
        $scope.$onRootScope('EVENT:AUTH.LOGGEDIN', function (event, obj) {
            $scope.initDataFromStateSvc();
        });

        $scope.$onRootScope('EVENT:MENU.CHANGED', function (event, menuTitle) {
            $scope.updateMenu(event, menuTitle);
        });

    }])

    .directive('ishaHeader', ['$location', 'stateSvc', function ($location, stateSvc) {

        return {
            replace: true,
            transclude: false,
            templateUrl: 'scripts/app/directives/templates/header.html',
            scope: true,
            controller: 'headerCtrl',

            link: function (scope, elem, attrs) {
                if (stateSvc.isAuthenticated()) {
                    scope.$emit('EVENT:AUTH.LOGGEDIN');
                    $location.path('/#/search');
                    scope.$apply();
                } else {
                    stateSvc.signIn();
                }
            }
        };
    }])